from django.conf import settings
from django.shortcuts import render_to_response
from django.template import RequestContext
from django.contrib.auth.forms import AuthenticationForm
from django.http import HttpResponseRedirect as redirect
from django.contrib.auth import authenticate
from StartGroup.models import Group
from docs.forms import DocUploadForm
import StartGroup.Constants
import connectpeople.Constants
from docs.models import Docs
from  django.http import QueryDict
from utils import activity_module, common_query, common_methods
import simplejson
from django.http import HttpResponse
import threading

# render form for Docs
def docsFormView(request, group_web_address):
    group_web_addr = group_web_address
    group_info = getGroupInfo(group_web_addr)              
    
    # Obtain user id
    userid = request.session[connectpeople.Constants.session_userid]
    
    # Get User object with permissions assigned
    permission = common_query.get_user_group_permission(userid, group_web_addr, False)
    
    # Group Info form initialization
    doc_form = DocUploadForm()
    return render_to_response("docs/docForm.html",
                      {'doc_form': doc_form,'group':group_info,
                       'permission':permission},
                      context_instance = RequestContext(request))
    

# Save the form
def docsView(request, group_web_address):
    
    group_web_addr = group_web_address
    group = getGroupInfo(group_web_addr)
    userid = request.session[connectpeople.Constants.session_userid]
    
    # Save the Doc    
    if request.method == 'POST':
        
        try:
            # Take the Action String to identif which action to perform
            action = request.POST.__getitem__('action')
        except:
            action = None        
        
        if action == "deleteDoc":
            # Delete Doc
            doc_id = request.POST.__getitem__('docid')
            Docs.objects.get(id=doc_id).delete()
            response = simplejson.dumps({'success':'success'})
        else:
            # Save and insert new row in table
            # Announcement form initialization
            doc_form = DocUploadForm(data=request.POST, files=request.FILES)            
            if doc_form.is_valid():
                doc = doc_form.save(userid, group)
                               
                # Get email ids of these users
                #recipient_list = common_query.getGroupMembersEmailIds(group_web_addr, connectpeople.Constants.new_announcement_email_flag_constant)
                # Compose subject for the email
                #subj = "New Announcement Posted"
                # Send Email alerts. Use threading to speed up things
                #new_comment_thread= threading.Thread(target=common_methods.send_email_helper, kwargs={'a_sender':Announcement, 'a_email':recipient_list, 'a_model':announcement, 'a_subject':subj, 'a_template':"email/newAnnouncementEmail.html"})
                #new_comment_thread.setDaemon(True)
                #new_comment_thread.start()
            else:
                print "invalid"
                # Get User object with permissions assigned
                permission = common_query.get_user_group_permission(userid, group_web_addr, False)
    
                return render_to_response("docs/docForm.html",
                      {'doc_form': doc_form,'group':group,
                       'permission':permission},
                      context_instance = RequestContext(request))                
    
    if request.is_ajax():
        return HttpResponse(response,
        content_type="application/javascript")
    
    # get all the group docs
    docs = Docs.objects.filter(group= group_web_addr).order_by('-created_date')    
    
    # Get User object with permissions assigned
    permission = common_query.get_user_group_permission(userid, group_web_addr, False)
                    
    return render_to_response("docs/docView.html",
                              {'docs': docs,'group':group, 'userid':userid, 'permission':permission},
                              context_instance = RequestContext(request))

# Helper function to obtain Group related to a group_web_address
def getGroupInfo(group_web_addr):
    return Group.objects.get(group_web_address= group_web_addr)